package me.yricky.cov_spectrum.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import me.yricky.chart.base.CoordinateDatasets
import me.yricky.chart.content.coordinate.coordinateDatasets
import me.yricky.cov_spectrum.app
import me.yricky.cov_spectrum.model.ApiModel
import me.yricky.cov_spectrum.model.beans.DateCountBean
import me.yricky.cov_spectrum.model.beans.QueryCase
import me.yricky.cov_spectrum.model.utils.datePrev
import me.yricky.cov_spectrum.model.utils.str

class CountQueryViewModel:ViewModel() {
    private val queryDataMap = mutableMapOf<QueryCase,MutableStateFlow<Result<CoordinateDatasets<DateCountBean>>>>()

    fun get(queryCase: QueryCase):StateFlow<Result<CoordinateDatasets<DateCountBean>>>{
        return queryDataMap[queryCase]?: MutableStateFlow(loading).also {
            queryDataMap[queryCase] = it
            refresh(queryCase)
        }
    }

    fun refresh(queryCase: QueryCase){
        viewModelScope.launch(Dispatchers.IO) {
            queryDataMap[queryCase]?.value = loading
            queryDataMap[queryCase]?.value = kotlin.runCatching{
                coordinateDatasets(
                    name = queryCase.toString(),
                    list = ApiModel.getDateCount(
                        accessKey = app.userCfg.get().accessKey,
                        dateFrom = datePrev(187L).str,
                        dateTo = datePrev(7L).str,
                        queryCase = queryCase
                    ).getOrThrow().data!!,
                    dataXValue = { it.epochDay },
                    dataYValue = { it.count }
                )
            }
        }
    }
    companion object{
        val loading = Result.failure<CoordinateDatasets<DateCountBean>>(Throwable("Loading"))
    }
}